package io.jt808.proto.down;

import io.norland.buffer.AutoBuffer;
import io.norland.annotations.Proto;
import io.norland.proto.IProto;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 补传分包请求
 */
@Proto("8003")
@Data
public class JT8003 implements IProto {

    /**
     * 原始消息包的第一个分包的流水号
     */

    private int responseMessageSerialNo;

    /**
     * 重传包总数
     */
    private byte retransmissionCount;
    /**
     * 重传包ID列表
     */
    private List<Integer> retransmissionPacketNos;

    public byte[] writeToBytes() {
        AutoBuffer buffer = new AutoBuffer();
        buffer.writeShort(responseMessageSerialNo);
        buffer.writeByte(retransmissionCount);
        for (int packetNo : retransmissionPacketNos)
            buffer.writeShort(packetNo);
        return buffer.array();
    }

    public void readFromBuf(AutoBuffer buffer) {
        responseMessageSerialNo = buffer.readUnsignedShort();
        retransmissionCount = buffer.readByte();
        retransmissionPacketNos = new ArrayList<>();
        while (buffer.isReadable())
            retransmissionPacketNos.add(buffer.readUnsignedShort());
    }

    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("原始消息的第一个分包流水号:")
                .append(responseMessageSerialNo)
                .append(",重传包数:")
                .append(retransmissionCount);
        if (retransmissionPacketNos != null && this.retransmissionPacketNos.size() > 0) {
            builder.append(",重传包Id列表:");
            for (int packetNo : retransmissionPacketNos) {
                builder.append(packetNo).append(",");
            }
        }
        return builder.toString();
    }

//    public static void main(String[] args) {
//        byte[] bytes = new byte[]{
//                0x00, 0x01,
//                0x02,
//                0x00, 0x03,
//                0x00, 0x04
//        };
//        AutoBuffer buffer = new AutoBuffer(bytes);
//        JT8003 jt8003 = new JT8003();
//        jt8003.readFromBuf(buffer);
//        System.out.printf(new String(bytes).equals(new String(jt8003.writeToBytes())) + "");
//    }
}